# -*- coding:utf-8 -*-
import flask
from flask_restful import Resource, reqparse, fields, marshal_with, inputs, abort
from app.api.services.service_user import ServiceUser
from app_config import WX_APPID, WX_SECRET
from app.util.WXBizDataCrypt import WXBizDataCrypt
from app.api.apis import very_token, auth_token, very_phone, very_role, very_password
from app.util.RedisClient import get_cache_key_value
import requests

resource_fields = {
	'username': fields.String,
	'id': fields.Integer,
	'nickname': fields.String,
	'email': fields.String,
	'role_type': fields.String,
	'mobile': fields.String,
	'school': fields.String
}


class ApiUser(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('username', type=str, required=True, help='ApiUser No username provided')

		super(ApiUser, self).__init__()

	# @marshal_with(resource_fields)
	def get(self):
		return ServiceUser().get_users()


class AuthLogin(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('login', type=inputs.regex('^[0-9]+$'), required=True, trim=True, nullable=False,
								   help="post No login provided")
		self.reqparse.add_argument('password', type=str, required=True, trim=True, nullable=True,
								   help='Password cannot be empty and at least eight characters')
		super(AuthLogin, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().auth_login(args['login'], args['password'])


class AuthLoginWx(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('userInfo', type=str, required=True, trim=True, nullable=False, help="wx serInfo")
		super(AuthLoginWx, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		print("====AuthLoginWx====", args)
		userInfo = eval(args["userInfo"])
		return ServiceUser().auth_login_wx(userInfo)


class AuthWx(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('code', type=str, required=True, trim=True, nullable=False, help="wx code request")
		self.reqparse.add_argument('encryptedData', type=str, required=True, trim=True, nullable=False,
								   help="wx encryptedData request")
		self.reqparse.add_argument('iv', type=str, required=True, trim=True, nullable=False, help="wx iv request")
		super(AuthWx, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		code = args["code"]
		print("args=", args)
		print("code=", code)
		url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' % (
			WX_APPID, WX_SECRET, code)
		r = requests.get(url)
		result = eval(r.text)
		print("===result==", result)
		if "errcode" in result:
			return result
		pc = WXBizDataCrypt(WX_APPID, result["session_key"])
		userInfo = pc.decrypt(args["encryptedData"], args["iv"])
		userInfo["openid"] = result["openid"]
		if "unionid" in result:
			userInfo["unionid"] = result["unionid"]
		return ServiceUser().auth_login_wx(userInfo)


class AuthToken(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('token', type=str, required=True, trim=True, nullable=True,
								   help='token cannot be empty')
		super(AuthToken, self).__init__()
	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().auth_jwt_token(args['token'])


class RefreshToken(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('token', type=str, required=True, trim=True, nullable=True,
								   help='token cannot be empty')
		super(RefreshToken, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().auth_refresh_token(args['token'])


class BatchUser(Resource):

	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('users', help='BatchUser No mobile provided')
		# self.reqparse.add_argument('passwd', type=str, required=True, help='BatchUser No passwd provided')
		# self.reqparse.add_argument('username', type=str, required=True, help='BatchUser No username provided')
		# self.reqparse.add_argument('email', type=str, required=True, help='BatchUser No email provided')
		super(BatchUser, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		data = []
		return ServiceUser().batch_users(data)


class AddUser(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('mobile', required=True, help='AddUser No mobile provided')
		self.reqparse.add_argument('password', type=str, required=True, help='AddUser No password provided')
		self.reqparse.add_argument('username', type=str, required=True, help='AddUser No username provided')
		self.reqparse.add_argument('nickname', type=str, help='AddUser No username provided')
		self.reqparse.add_argument('email', type=str, help='AddUser No email provided')
		self.reqparse.add_argument('city', type=str, help='AddUser No city provided')
		self.reqparse.add_argument('industry', type=str, help='AddUser No industry provided')
		self.reqparse.add_argument('gender', type=str, help='AddUser No gender provided')
		self.reqparse.add_argument('avatar', type=str, help='AddUser No avatar provided')
		super(AddUser, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().add_user(args)


class EditUser(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('username', type=str, help='AddUser No username provided')
		self.reqparse.add_argument('nickname', type=str, help='AddUser No username provided')
		self.reqparse.add_argument('email', type=str, help='AddUser No email provided')
		self.reqparse.add_argument('city', type=str, help='AddUser No city provided')
		self.reqparse.add_argument('industry', type=str, help='AddUser No industry provided')
		self.reqparse.add_argument('gender', type=str, help='AddUser No gender provided')
		self.reqparse.add_argument('avatar', type=str, help='AddUser No avatar provided')
		self.reqparse.add_argument('token', type=very_token, help='token is error')
		super(EditUser, self).__init__()

	def post(self, id):
		args = self.reqparse.parse_args(strict=True)
		temp = dict()
		temp["id"] = id
		del args["token"]
		return ServiceUser().edit_user(args, **temp)

	@auth_token(flask.request)
	def delete(self, id):
		temp = dict()
		temp["id"] = id
		return ServiceUser().delete_user(**temp)


class AuthPhone(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('phone', type=very_phone, required=True, help='The number you entered is incorrect.')
		super(AuthPhone, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().auth_phone(args["phone"])


class BindPhone(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('phone', type=very_phone, required=True, help='您输入的手机号有误.')
		self.reqparse.add_argument('code', required=True, help='The code is null or you entered is incorrect.')
		self.reqparse.add_argument('token', type=very_token, required=True)
		self.reqparse.add_argument('password', type=very_password)
		self.reqparse.add_argument('password_conf', type=very_password)
		super(BindPhone, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		if "code" in args.keys():
			redis_code = get_cache_key_value(args["phone"])
			if str(args["code"]) != redis_code:
				return {"errcode": 400, "errmsg": "您输入的验证码有误"}
		password = args["password"]
		password_conf = args["password"]
		if password != password_conf:
			return {"errcode": 400, "errmsg": "两次输入的密码不一致"}
		temp = {"id": args["token"]["id"], "mobile": args["phone"]}
		if password is not None:
			temp["passwd"] = password
		return ServiceUser().bind_phone(temp)


class UpdateBindPhone(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('phone', type=very_phone, required=True, help='The phone you entered is incorrect.')
		self.reqparse.add_argument('code', required=True, help='The code is null or you entered is incorrect.')
		self.reqparse.add_argument('token', type=very_token, required=True)
		super(UpdateBindPhone, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		if "code" in args.keys():
			redis_code = get_cache_key_value(args["phone"])
			if str(args["code"]) != redis_code:
				return {"errcode": 400, "errmsg": "The code you entered is incorrect"}

		temp = {"id": args["token"]["id"], "mobile": args["phone"]}

		return ServiceUser().update_bind_phone(temp)


class UpdateRole(Resource):
	def __init__(self):
		self.reqparse = reqparse.RequestParser()
		self.reqparse.add_argument('user_id', type=int, required=True,  help='UpdateRole No user_id provided')
		self.reqparse.add_argument('role', type=very_role,  required=True)
		self.reqparse.add_argument('token', type=very_token, required=True, help='Token has expired, please retrieve it')
		super(UpdateRole, self).__init__()

	def post(self):
		args = self.reqparse.parse_args(strict=True)
		return ServiceUser().edit_user(dict(role_type=args["role"]), **dict(id=args["user_id"]))
